const path = require('path')
const Webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const AutoPrefixer = require('autoprefixer')
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
const vueLoaderPlugin = require('vue-loader/lib/plugin')

module.exports = {
  entry: {
    main: path.resolve(__dirname,'/src/main.js'), // 多入口文件
    header: path.resolve(__dirname,'/src/header.js'),
  },
  output: {
    filename: '[name].[hash:8].js',// 打包后的文件名称
    path: path.resolve(__dirname,'dist')  // 打包后的目录
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['style-loader','css-loader'] // 从右向左解析
      },
      {
        test: /\.less$/,
        use: ['style-loader',MiniCssExtractPlugin.loader,'css-loader','postcss-loader','less-loader'] // 从右向左解析
      },
      // webpack5新特性
      {
        test: /\.(jpe?g|png|gif)$/i,
        type: 'asset/resource',
        generator: {
          filename: 'static/images/[hash][ext][query]'
        },
        parser: {
          dataUrlCondition: {
            maxSize: 10 * 1024 // 10kb
          }
        }
      },
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        type: 'asset/inline',
        generator: {
          filename: 'static/media/[hash][ext][query]'
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/i,
        type: 'asset/inline',
        generator: {
          filename: 'static/font/[hash][ext][query]'
        }
      },
      {
        test: /\.vue$/,
        use: ['vue-loader'],
        include: [path.resolve(__dirname,'src')],
        exclude: /node_modules/
      } 
    ],

  },
  resolve: {  // 设置模块如何被解析
    alias: {  // 创建 import 或 require 的别名，来确保模块引入变得更简单
      'vue$': 'vue/dist/vue.runtime.esm.js',
      ' @': path.resolve(__dirname,'./src')
    },
    extensions:['*','.js','.json','.vue']
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname,'public/index.html'),
      filename: 'index.html',
      chunks: ['main'] // 与入口文件对应的模块名
    }),
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname,'public/header.html'),
      filename: 'header.html',
      chunks: ['header'] // 与入口文件对应的模块名
    }),
    new CleanWebpackPlugin(), // 清空dist文件
    AutoPrefixer, // 引入前缀组件即可
    new MiniCssExtractPlugin({
      filename: "[name].[hash].css",
      chunkFilename: "[id].css",
    }),
    new vueLoaderPlugin(), // 加载vue plugin
    new Webpack.HotModuleReplacementPlugin()
  ]
}